<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编码" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合作方编码" prop="partnerCode" label-width="120px">
        <el-input
          v-model="queryParams.partnerCode"
          placeholder="请输入合作方编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['GroupLeaderOrders:GroupLeaderOrders:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleCreateSettlement"
          v-hasPermi="['settlement:settlement:add']"
          :disabled="!canCreateSettlement"
        >创建结算单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GroupLeaderOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编码" align="center" prop="orderCode" />
      <el-table-column label="合作方编码" align="center" prop="partnerCode" />
      <el-table-column label="订单金额(元)" align="right" prop="orderAmount" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <el-tag :type="primary" disable-transitions>
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['GroupLeaderOrders:GroupLeaderOrders:detail']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 订单详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="600px" append-to-body>
      <el-form :model="detailForm" label-width="120px" disabled>
        <el-form-item label="订单编码">
          <el-input v-model="detailForm.orderCode" />
        </el-form-item>
        <el-form-item label="合作方编码">
          <el-input v-model="detailForm.partnerCode" />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="detailForm.orderAmount" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="detailForm.orderStatus" placeholder="请选择订单状态">
            <el-option label="待处理" value="pending" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单日期">
          <el-input v-model="detailForm.orderDate" />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input v-model="detailForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 创建结算单对话框 -->
    <el-dialog title="创建结算单" v-model="settlementOpen" width="600px" append-to-body>
      <el-form ref="settlementRef" :model="settlementForm" :rules="settlementRules" label-width="100px">
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="settlementForm.partnerCode" placeholder="请输入合作方编码" disabled />
        </el-form-item>
        <el-form-item label="订单总金额" prop="orderAmount">
          <el-input v-model="settlementForm.orderAmount" placeholder="请输入结算总金额" disabled />
        </el-form-item>
        <el-form-item label="结算方式" prop="settlementMethod">
          <el-input v-model="settlementForm.settlementMethod" placeholder="请输入结算方式,0为支付宝，1为微信，2为银联" />
        </el-form-item>
        <el-form-item label="协议编码" prop="agreementCode">
          <el-input v-model="settlementForm.agreementCode" placeholder="请输入协议编码" />
        </el-form-item>
        <el-form-item label="货币单位" prop="currencyUnit">
          <el-input v-model="settlementForm.currencyUnit" placeholder="请输入货币单位" />
        </el-form-item>
        <el-form-item label="结算状态" prop="settlementStatus">
          <el-input v-model="settlementForm.settlementStatus" placeholder="请输入结算状态" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="settlementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">结算详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSettlementDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSettlementDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="settlementDetailList" :row-class-name="rowSettlementDetailIndex" @selection-change="handleSettlementDetailSelectionChange" ref="settlementDetailTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="订单编码" align="center" prop="orderCode" />
          <el-table-column label="订单金额" align="center" prop="orderAmount" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettlementForm">确 定</el-button>
          <el-button @click="cancelSettlement">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GroupLeaderOrders">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listGroupLeaderOrders, getGroupLeaderOrders, createSettlement, updateOrderStatus } from "@/api/settled/GroupLeaderOrders";

const { proxy } = getCurrentInstance();

const GroupLeaderOrdersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const selectedOrders = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailOpen = ref(false);
const detailTitle = ref("");
const detailForm = ref({});
const settlementOpen = ref(false);
const canCreateSettlement = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderCode: null,
    partnerCode: null,
    orderStatus: null,
    orderDate: null,
  },
  rules: {
    orderCode: [
      { required: true, message: "订单编码，主键不能为空", trigger: "blur" }
    ],
    partnerCode: [
      { required: true, message: "合作方编码，外键不能为空", trigger: "blur" }
    ],
    orderAmount: [
      { required: true, message: "订单金额不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    orderDate: [
      { required: true, message: "订单日期不能为空", trigger: "blur" }
    ],
  },
  settlementForm: {
    partnerCode: '',
    orderAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    taxRate: 0,
    taxAmount: 0,
    settlementStatus: '',
    remark: ''
  },
  settlementRules: {
    settlementMethod: [
      { required: true, message: "结算方式不能为空", trigger: "blur" }
    ],
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
    currencyUnit: [
      { required: true, message: "货币单位不能为空", trigger: "blur" }
    ],
    settlementStatus: [
      { required: true, message: "结算状态不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注信息不能为空", trigger: "blur" }
    ],
  },
  settlementDetailList: [] // 初始化为空数组
});

const { queryParams, form, rules, settlementForm, settlementRules, settlementDetailList } = toRefs(data);

/** 查询博主订单列表 */
function getList() {
  loading.value = true;
  listGroupLeaderOrders(queryParams.value).then(response => {
    GroupLeaderOrdersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderCode: null,
    partnerCode: null,
    orderAmount: null,
    orderStatus: null,
    orderDate: null,
    creator: null,
    modifyTime: null,
    lastModifiedBy: null,
    remark: null
  };
  proxy.resetForm("GroupLeaderOrdersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedOrders.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;

  if (selection.length > 0) {
    const partnerCode = selection[0].partnerCode;
    canCreateSettlement.value = selection.every(order => order.partnerCode === partnerCode);
    settlementForm.value.partnerCode = partnerCode;
    settlementForm.value.orderAmount = selection.reduce((sum, order) => sum + parseFloat(order.orderAmount), 0);
  } else {
    canCreateSettlement.value = false;
    settlementForm.value.partnerCode = '';
    settlementForm.value.orderAmount = 0;
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('GroupLeaderOrders/GroupLeaderOrders/export', {
    ...queryParams.value
  }, `GroupLeaderOrders_${new Date().getTime()}.xlsx`);
}

// 创建结算单按钮操作
function handleCreateSettlement() {
  if (selectedOrders.value.length === 0) {
    proxy.$modal.msgWarning("请先选择订单");
    return;
  }
  settlementForm.value.partnerCode = selectedOrders.value[0].partnerCode;
  settlementForm.value.orderAmount = selectedOrders.value.reduce((sum, order) => sum + parseFloat(order.orderAmount), 0);
  settlementDetailList.value = selectedOrders.value.map((order, index) => ({
    index: index + 1,
    orderCode: order.orderCode,
    orderAmount: order.orderAmount
  }));
  settlementOpen.value = true;
}

// 取消创建结算单
function cancelSettlement() {
  settlementOpen.value = false;
  resetSettlementForm();
}

// 重置结算单表单
function resetSettlementForm() {
  settlementForm.value = {
    partnerCode: '',
    orderAmount: 0,
    remark: ''
  };
  proxy.resetForm("settlementRef");
}

// 提交结算单表单
function submitSettlementForm() {
  proxy.$refs["settlementRef"].validate(valid => {
    if (valid) {
      const dataToSend = {
        ...settlementForm.value,
        settlementDetailList: settlementDetailList.value
      };
      createSettlement(dataToSend).then(response => {
        proxy.$modal.msgSuccess("结算单创建成功");

        // 更新订单状态为“已经结算”
        const orderCodes = selectedOrders.value.map(order => order.orderCode);
        orderCodes.forEach(orderCode => {
          updateOrderStatus(orderCode, '已经结算').then(() => {
            // 更新前端数据
            const orderIndex = GroupLeaderOrdersList.value.findIndex(order => order.orderCode === orderCode);
            if (orderIndex !== -1) {
              GroupLeaderOrdersList.value[orderIndex].orderStatus = '已经结算';
            }
          }).catch(error => {
            console.error("Error updating order status:", error);
            proxy.$modal.msgError("更新订单状态失败");
          });
        });

        settlementOpen.value = false;
        resetSettlementForm();
        getList();
      }).catch(error => {
        proxy.$modal.msgError("结算单创建失败");
      });
    }
  });
}

// 添加结算详情
function handleAddSettlementDetail() {
  // 这里可以添加具体的逻辑，例如打开一个对话框来添加新的结算详情
}

// 删除结算详情
function handleDeleteSettlementDetail() {
  // 这里可以添加具体的逻辑，例如删除选中的结算详情
}

// 行索引
function rowSettlementDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
  return '';
}

// 结算详情选择变化
function handleSettlementDetailSelectionChange(selection) {
  // 这里可以添加具体的逻辑，例如记录选中的结算详情
}

// 详情按钮操作
function handleDetail(row) {
  getGroupLeaderOrders(row.orderCode).then(response => {
    detailForm.value = response.data;
    detailTitle.value = `订单详情 - ${row.orderCode}`;
    detailOpen.value = true;
  });
}

getList();
</script>
